<template>
  <div class="task-review-container">
    <h1 class="page-title">任务审核</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="review-content">
      <el-card class="task-info-card">
        <div class="task-header">
          <h2>{{ task.title }}</h2>
          <el-tag :type="getStatusType(task.status)">{{ task.status }}</el-tag>
        </div>
        <p class="task-description">{{ task.description }}</p>
        
        <div class="task-details">
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">任务ID：</span>
              <span class="value">{{ task.id }}</span>
            </div>
            <div class="detail-item">
              <span class="label">执行人：</span>
              <span class="value">{{ task.executor }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ formatDateTime(task.startTime) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">完成时间：</span>
              <span class="value">{{ formatDateTime(task.completionTime) }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="label">执行耗时：</span>
              <span class="value">{{ task.duration }}</span>
            </div>
            <div class="detail-item">
              <span class="label">审核状态：</span>
              <span class="value">
                <el-tag :type="getReviewStatusType(task.reviewStatus)">{{ task.reviewStatus }}</el-tag>
              </span>
            </div>
          </div>
        </div>

        <div class="deliverables-section" v-if="task.deliverables && task.deliverables.length > 0">
          <h3>提交的成果物</h3>
          <el-table :data="task.deliverables" style="width: 100%">
            <el-table-column prop="name" label="文件名" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="size" label="大小" />
            <el-table-column prop="uploadTime" label="上传时间">
              <template #default="scope">
                {{ formatDateTime(scope.row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" size="small" @click="previewDeliverable(scope.row)">预览</el-button>
                <el-button type="success" size="small" @click="downloadDeliverable(scope.row)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="execution-summary">
          <h3>执行摘要</h3>
          <div class="summary-content" v-html="task.executionSummary"></div>
        </div>

        <div class="review-section" v-if="task.reviewStatus === '待审核'">
          <h3>审核评价</h3>
          <el-form :model="reviewForm" label-position="top">
            <el-form-item label="完成质量评分">
              <el-rate
                v-model="reviewForm.qualityRating"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="完成效率评分">
              <el-rate
                v-model="reviewForm.efficiencyRating"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="协作评分">
              <el-rate
                v-model="reviewForm.collaborationRating"
                :colors="rateColors"
                show-score
              />
            </el-form-item>
            <el-form-item label="审核评语">
              <el-input
                v-model="reviewForm.comments"
                type="textarea"
                :rows="4"
                placeholder="请对任务执行情况进行评价和反馈"
              />
            </el-form-item>
            <el-form-item label="审核结果">
              <el-radio-group v-model="reviewForm.result">
                <el-radio label="approved">通过</el-radio>
                <el-radio label="rejected">不通过</el-radio>
                <el-radio label="needRevision">需要修改</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="reviewForm.result === 'needRevision'">
              <el-input
                v-model="reviewForm.revisionRequirements"
                type="textarea"
                :rows="3"
                placeholder="请描述需要修改的内容"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitReview">提交审核</el-button>
              <el-button type="default" @click="resetReview">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="review-result" v-else>
          <h3>审核结果</h3>
          <div class="result-details">
            <div class="rating-item">
              <span class="label">完成质量：</span>
              <el-rate
                v-model="task.review.qualityRating"
                disabled
                :colors="rateColors"
                show-score
              />
            </div>
            <div class="rating-item">
              <span class="label">完成效率：</span>
              <el-rate
                v-model="task.review.efficiencyRating"
                disabled
                :colors="rateColors"
                show-score
              />
            </div>
            <div class="rating-item">
              <span class="label">协作情况：</span>
              <el-rate
                v-model="task.review.collaborationRating"
                disabled
                :colors="rateColors"
                show-score
              />
            </div>
            <div class="review-comments">
              <span class="label">审核评语：</span>
              <p class="value">{{ task.review.comments }}</p>
            </div>
            <div class="review-result-tag">
              <span class="label">审核结果：</span>
              <el-tag :type="getReviewResultType(task.review.result)">{{ getReviewResultText(task.review.result) }}</el-tag>
            </div>
            <div class="review-revision" v-if="task.review.result === 'needRevision'">
              <span class="label">修改要求：</span>
              <p class="value">{{ task.review.revisionRequirements }}</p>
            </div>
            <div class="reviewer-info">
              <span class="label">审核人：</span>
              <span class="value">{{ task.review.reviewer }}</span>
            </div>
            <div class="review-time">
              <span class="label">审核时间：</span>
              <span class="value">{{ formatDateTime(task.review.reviewTime) }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialogVisible" :title="currentDeliverable.name" width="80%">
      <div class="preview-content">
        <!-- 这里可以根据文件类型显示不同的预览组件 -->
        <div v-if="currentDeliverable.type === 'image'" class="image-preview">
          <img :src="currentDeliverable.url" alt="Preview" style="max-width: 100%;" />
        </div>
        <div v-else-if="currentDeliverable.type === 'pdf'" class="pdf-preview">
          <iframe :src="currentDeliverable.url" style="width: 100%; height: 600px;"></iframe>
        </div>
        <div v-else class="text-preview">
          <p>无法预览此类型文件，请下载后查看。</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
  name: 'TaskReview',
  setup() {
    const route = useRoute()
    const executionId = route.params.id
    const task = ref({})
    const loading = ref(true)
    const error = ref(null)
    const previewDialogVisible = ref(false)
    const currentDeliverable = ref({})
    
    const reviewForm = reactive({
      qualityRating: 3,
      efficiencyRating: 3,
      collaborationRating: 3,
      comments: '',
      result: 'approved',
      revisionRequirements: ''
    })
    
    const rateColors = {
      2: '#E6A23C',
      4: '#67C23A',
      5: '#409EFF'
    }

    const fetchTaskData = async () => {
      try {
        loading.value = true
        // 这里替换为实际的 API 调用
        // const response = await fetch(`/api/executions/${executionId}/review`)
        // task.value = await response.json()
        
        // 模拟数据
        setTimeout(() => {
          task.value = {
            id: executionId,
            title: '实现任务进度跟踪功能',
            description: '开发用于跟踪项目任务进度的界面，包括进度条、里程碑和状态更新功能',
            status: '已完成',
            executor: '李四',
            startTime: '2024-05-05T09:30:00',
            completionTime: '2024-05-10T16:45:00',
            duration: '3天7小时15分钟',
            reviewStatus: '待审核', // 可选值：'待审核'、'已审核'、'需修改'
            executionSummary: `<p>按照需求规格说明书，完成了以下功能：</p>
              <ul>
                <li>实现了任务进度可视化展示</li>
                <li>支持里程碑的显示和更新</li>
                <li>添加了状态颜色标识和任务详情展示</li>
                <li>实现了响应式布局，适配不同设备</li>
              </ul>
              <p>遇到的主要问题是动画效果在某些浏览器上不流畅，已通过降低动画复杂度解决。所有功能测试通过，代码已按要求进行注释。</p>`,
            deliverables: [
              { 
                name: '任务进度组件.vue', 
                type: 'code', 
                size: '24KB',
                url: '#',
                uploadTime: '2024-05-10T16:30:00' 
              },
              { 
                name: '实现截图.png', 
                type: 'image', 
                size: '320KB',
                url: '#',
                uploadTime: '2024-05-10T16:35:00' 
              },
              { 
                name: '测试报告.pdf', 
                type: 'pdf', 
                size: '1.2MB',
                url: '#',
                uploadTime: '2024-05-10T16:40:00' 
              }
            ],
            // 如果已审核，则包含review对象
            // review: {
            //   qualityRating: 4.5,
            //   efficiencyRating: 5,
            //   collaborationRating: 4,
            //   comments: '完成质量很高，代码结构清晰，但还有优化空间',
            //   result: 'approved', // 'approved'、'rejected'、'needRevision'
            //   revisionRequirements: '',
            //   reviewer: '张三',
            //   reviewTime: '2024-05-11T10:20:00'
            // }
          }
          loading.value = false
        }, 1000)
      } catch (err) {
        error.value = '获取任务审核数据失败'
        loading.value = false
        console.error(err)
      }
    }

    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    }

    const getStatusType = (status) => {
      switch (status) {
        case '已完成':
          return 'success'
        case '进行中':
          return 'primary'
        case '未开始':
          return 'info'
        default:
          return 'info'
      }
    }

    const getReviewStatusType = (status) => {
      switch (status) {
        case '已审核':
          return 'success'
        case '待审核':
          return 'warning'
        case '需修改':
          return 'danger'
        default:
          return 'info'
      }
    }

    const getReviewResultType = (result) => {
      switch (result) {
        case 'approved':
          return 'success'
        case 'rejected':
          return 'danger'
        case 'needRevision':
          return 'warning'
        default:
          return 'info'
      }
    }

    const getReviewResultText = (result) => {
      switch (result) {
        case 'approved':
          return '通过'
        case 'rejected':
          return '不通过'
        case 'needRevision':
          return '需要修改'
        default:
          return '未知'
      }
    }

    const submitReview = () => {
      if (!reviewForm.comments) {
        ElMessage.warning('请填写审核评语')
        return
      }

      if (reviewForm.result === 'needRevision' && !reviewForm.revisionRequirements) {
        ElMessage.warning('请填写修改要求')
        return
      }

      // 实际应用中应调用 API 来提交审核
      // 模拟审核提交成功
      task.value.reviewStatus = reviewForm.result === 'needRevision' ? '需修改' : '已审核'
      task.value.review = {
        qualityRating: reviewForm.qualityRating,
        efficiencyRating: reviewForm.efficiencyRating,
        collaborationRating: reviewForm.collaborationRating,
        comments: reviewForm.comments,
        result: reviewForm.result,
        revisionRequirements: reviewForm.revisionRequirements,
        reviewer: '当前用户',
        reviewTime: new Date().toISOString()
      }

      ElMessage.success('审核已提交')
    }

    const resetReview = () => {
      reviewForm.qualityRating = 3
      reviewForm.efficiencyRating = 3
      reviewForm.collaborationRating = 3
      reviewForm.comments = ''
      reviewForm.result = 'approved'
      reviewForm.revisionRequirements = ''
    }

    const previewDeliverable = (deliverable) => {
      currentDeliverable.value = deliverable
      previewDialogVisible.value = true
    }

    const downloadDeliverable = (deliverable) => {
      // 在实际应用中应该下载文件
      console.log('下载文件:', deliverable)
      ElMessage.success(`开始下载: ${deliverable.name}`)
    }

    onMounted(() => {
      fetchTaskData()
    })

    return {
      task,
      loading,
      error,
      reviewForm,
      rateColors,
      previewDialogVisible,
      currentDeliverable,
      formatDateTime,
      getStatusType,
      getReviewStatusType,
      getReviewResultType,
      getReviewResultText,
      submitReview,
      resetReview,
      previewDeliverable,
      downloadDeliverable
    }
  }
}
</script>

<style scoped>
.task-review-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.task-info-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-description {
  margin-bottom: 20px;
  color: #606266;
}

.task-details {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.detail-item {
  flex-basis: 48%;
}

.label {
  font-size: 14px;
  color: #909399;
  margin-right: 5px;
}

.value {
  font-size: 16px;
  font-weight: 500;
}

.deliverables-section,
.execution-summary,
.review-section,
.review-result {
  margin-top: 30px;
}

h3 {
  margin-bottom: 15px;
  font-size: 18px;
  font-weight: 500;
}

.summary-content {
  line-height: 1.6;
}

.result-details {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.rating-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.rating-item .label {
  width: 100px;
}

.review-comments {
  margin: 20px 0;
}

.review-comments .label {
  display: block;
  margin-bottom: 10px;
}

.review-comments .value {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.review-result-tag,
.reviewer-info,
.review-time {
  margin-bottom: 15px;
}

.review-revision {
  margin: 20px 0;
}

.review-revision .label {
  display: block;
  margin-bottom: 10px;
}

.review-revision .value {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.loading-container,
.error-container {
  margin: 30px 0;
}
</style> 